package com.copote.pdfutils.common;


import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.properties.TextAlignment;
import lombok.AllArgsConstructor;

/**
 * @ClassName: PageMarker
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author: 湖南湘邮科技股份有限公司/RedStar
 * @date: 2023/9/18 16:17
 * @Copyright: 2019 2000 - 2022 HuNan Copote Science & Technology CO., LTD. All Rights Reserved.<br/>
 * 注意：本内容仅限于湖南湘邮科技股份有限公司内部传阅，禁止外泄以及用于其他的商业目的
 */
@AllArgsConstructor
public class PageMarker implements IEventHandler {

    private int pageTotal;
    private PdfFont pdfFont;

    @Override
    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdf = docEvent.getDocument();
        PdfPage page = docEvent.getPage();
        Rectangle pageSize = page.getPageSize();
        PdfCanvas pdfCanvas = new PdfCanvas(page.getLastContentStream(), page.getResources(), pdf);
        Canvas canvas = new Canvas(pdfCanvas, pageSize, true);
        float x = (pageSize.getLeft() + pageSize.getRight()) / 2;
        float y = pageSize.getBottom() + 15;
        String tail = "第" + pdf.getPageNumber(page) + "页";
        if (pageTotal > 0) {
            tail = tail + "/共" + pageTotal + "页";
        }
        Paragraph p = new Paragraph(tail).setFontSize(11).setFont(pdfFont);
        canvas.showTextAligned(p, x, y, TextAlignment.CENTER);
        canvas.close();
    }
}
